package com.smart.community.property.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.smart.community.commons.annotation.ApiLog;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.enums.ApiLogOperationType;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.property.service.DataScopeService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据权限控制控制器
 * 
 * 功能说明： 1. 提供数据权限查询和检查功能 2. 支持权限申请和状态查询 3. 提供权限缓存管理功能
 * 
 * 权限控制： - 根据"智慧社区微服务架构总览.md"文档，Controller层不进行权限检查 - 权限检查由Service层处理，确保数据权限正确过滤
 * 
 * @author Wu.Liang
 * @since 2025-01-29
 */
@Slf4j
@RestController
@RequestMapping("/property/data-scope")
@Tag(name = "数据权限控制", description = "数据权限控制相关接口")
public class DataScopeController {

	@Autowired
	private DataScopeService dataScopeService;

	/**
	 * 获取当前用户数据权限信息
	 */
	@GetMapping("/current-user")
	@Operation(summary = "获取当前用户数据权限信息")
	public Result<DataScopeInfo> getCurrentUserDataScope() throws Exception {
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		return Result.success("获取成功", dataScopeInfo);
	}

	/**
	 * 获取用户可访问的社区列表
	 */
	@GetMapping("/user-communities")
	@Operation(summary = "获取用户可访问的社区列表")
	public Result<List<Long>> getUserCommunities() throws Exception {
		List<Long> communityIds = dataScopeService.getCurrentUserCommunityIds();
		return Result.success("获取成功", communityIds);
	}

	/**
	 * 获取用户关联的物业公司信息
	 */
	@GetMapping("/user-property-company")
	@Operation(summary = "获取用户关联的物业公司信息")
	public Result<Map<String, Object>> getUserPropertyCompany() throws Exception {
		DataScopeInfo dataScopeInfo = dataScopeService.getCurrentUserDataScope();
		Map<String, Object> result = new HashMap<>();
		result.put("isPropertyCompanyUser", dataScopeInfo.isPropertyCompanyUser());
		result.put("propertyCompanyIds", dataScopeInfo.getPropertyCompanyIds());
		return Result.success("获取成功", result);
	}

	/**
	 * 检查用户是否有指定社区权限
	 */
	@GetMapping("/community/{communityId}/check")
	@Operation(summary = "检查用户是否有指定社区权限")
	public Result<Map<String, Boolean>> checkCommunityPermission(@PathVariable Long communityId) throws Exception {
		boolean hasPermission = dataScopeService.hasCommunityPermission(SecurityUtils.getCurrentUserId(), communityId);
		Map<String, Boolean> result = new HashMap<>();
		result.put("hasPermission", hasPermission);
		return Result.success("检查成功", result);
	}

	/**
	 * 批量检查用户社区权限
	 */
	@PostMapping("/community/batch-check")
	@Operation(summary = "批量检查用户社区权限")
	public Result<Map<String, List<Long>>> batchCheckCommunityPermissions(@RequestBody Map<String, List<Long>> request)
			throws Exception {
		List<Long> communityIds = request.get("communityIds");
		if (communityIds == null || communityIds.isEmpty()) {
			return Result.fail("社区ID列表不能为空");
		}

		List<Long> authorizedCommunityIds = dataScopeService.getAuthorizedCommunityIds(SecurityUtils.getCurrentUserId(),
				communityIds);

		Map<String, List<Long>> result = new HashMap<>();
		result.put("authorizedCommunityIds", authorizedCommunityIds);
		return Result.success("批量检查成功", result);
	}

	/**
	 * 检查用户是否为物业公司人员
	 */
	@GetMapping("/check-property-company-user")
	@Operation(summary = "检查用户是否为物业公司人员")
	public Result<Map<String, Boolean>> checkPropertyCompanyUser() throws Exception {
		boolean isPropertyCompanyUser = dataScopeService.isCurrentUserPropertyCompanyUser();
		Map<String, Boolean> result = new HashMap<>();
		result.put("isPropertyCompanyUser", isPropertyCompanyUser);
		return Result.success("检查成功", result);
	}

	/**
	 * 获取物业公司关联的社区列表
	 */
	@GetMapping("/property-company/{propertyCompanyId}/communities")
	@Operation(summary = "获取物业公司关联的社区列表")
	public Result<List<Map<String, Object>>> getPropertyCompanyCommunities(@PathVariable Long propertyCompanyId)
			throws Exception {
		// 验证用户是否有权限查看该物业公司的信息
		Long currentUserId = SecurityUtils.getCurrentUserId();
		log.info("获取物业公司关联的社区列表，物业公司ID: {}, 当前用户ID: {}", propertyCompanyId, currentUserId);

		List<Long> communityIds = dataScopeService.getUserCommunityIds(SecurityUtils.getCurrentUserId());

		// 这里应该返回更详细的社区信息
		List<Map<String, Object>> communities = communityIds.stream().map(id -> {
			Map<String, Object> community = new HashMap<>();
			community.put("communityId", id);
			community.put("communityName", "社区" + id);
			community.put("status", 1);
			return community;
		}).collect(Collectors.toList());

		return Result.success("获取成功", communities);
	}

	@ApiLog(logTitle = "提交权限申请", logType = 2, // 操作日志
			moduleName = "物业管理", operationType = ApiLogOperationType.ADD)
	@PostMapping("/permission-request")
	@Operation(summary = "提交权限申请")
	public Result<Map<String, String>> submitPermissionRequest(@RequestBody Map<String, Object> request)
			throws Exception {
		// 这里应该实现权限申请逻辑
		String requestId = "REQ" + System.currentTimeMillis();
		log.info("收到权限申请，申请ID: {}, 申请内容: {}", requestId, request);

		Map<String, String> result = new HashMap<>();
		result.put("requestId", requestId);
		result.put("success", "true");
		return Result.success("提交成功", result);
	}

	/**
	 * 查询权限申请状态
	 */
	@GetMapping("/permission-request/{requestId}")
	@Operation(summary = "查询权限申请状态")
	public Result<Map<String, Object>> getPermissionRequestStatus(@PathVariable String requestId) throws Exception {
		// 这里应该实现权限申请状态查询逻辑
		Map<String, Object> status = new HashMap<>();
		status.put("requestId", requestId);
		status.put("status", "pending");
		status.put("result", null);
		status.put("processTime", null);
		status.put("remark", "申请正在处理中");
		return Result.success("查询成功", status);
	}

	/**
	 * 获取权限异常详情
	 */
	@GetMapping("/exception/{errorCode}")
	@Operation(summary = "获取权限异常详情")
	public Result<Map<String, String>> getPermissionExceptionDetail(@PathVariable String errorCode) throws Exception {
		Map<String, String> exceptionDetail = new HashMap<>();
		exceptionDetail.put("errorCode", errorCode);

		switch (errorCode) {
		case "DATA_SCOPE_001":
			exceptionDetail.put("message", "您没有权限访问指定社区的数据");
			exceptionDetail.put("solution", "请联系物业公司管理员分配社区权限");
			exceptionDetail.put("contactInfo", "物业公司管理员");
			break;
		case "DATA_SCOPE_002":
			exceptionDetail.put("message", "您没有权限访问指定物业公司的数据");
			exceptionDetail.put("solution", "请联系系统管理员分配物业公司权限");
			exceptionDetail.put("contactInfo", "系统管理员");
			break;
		case "DATA_SCOPE_003":
			exceptionDetail.put("message", "非物业公司人员不能查看本页面数据");
			exceptionDetail.put("solution", "请联系系统管理员关联物业公司");
			exceptionDetail.put("contactInfo", "管理员邮箱：admin@smart-community.com");
			break;
		default:
			exceptionDetail.put("message", "未知权限错误");
			exceptionDetail.put("solution", "请联系系统管理员");
			exceptionDetail.put("contactInfo", "系统管理员");
		}

		return Result.success("获取成功", exceptionDetail);
	}

	@ApiLog(logTitle = "刷新用户权限缓存", logType = 2, // 操作日志
			moduleName = "物业管理", operationType = ApiLogOperationType.UPDATE)
	@PostMapping("/refresh-cache")
	@Operation(summary = "刷新用户权限缓存")
	public Result<Map<String, Boolean>> refreshUserPermissionCache() throws Exception {
		Long userId = SecurityUtils.getCurrentUserId();
		dataScopeService.refreshUserPermissionCache(userId);

		Map<String, Boolean> result = new HashMap<>();
		result.put("success", true);
		return Result.success("刷新成功", result);
	}

	@ApiLog(logTitle = "清除用户权限缓存", logType = 2, // 操作日志
			moduleName = "物业管理", operationType = ApiLogOperationType.DELETE)
	@DeleteMapping("/clear-cache")
	@Operation(summary = "清除用户权限缓存")
	public Result<Map<String, Boolean>> clearUserPermissionCache(@RequestParam(required = false) Long userId)
			throws Exception {
		if (userId == null) {
			userId = SecurityUtils.getCurrentUserId();
		}

		dataScopeService.clearUserPermissionCache(userId);

		Map<String, Boolean> result = new HashMap<>();
		result.put("success", true);
		return Result.success("清除成功", result);
	}
}
